<?php

function json($data=[])
{
    count($data)<=0 && $data =new \StdClass();
    header('Content-Type:application/json');    
    return json_encode($data);
}


function returnJson($msg,$code=0,$data=[])
{
    count($data)<=0 && $data =new \StdClass();
    header('Content-Type:application/json');    
    die(json_encode([
        'code'     =>  $code,
        'msg'       =>  $msg,
        'result'    =>  $data
    ]));
}

use \chenbool\JWT\JWT;
// 加密token
function jwt_encode($key=null){
    $key || $key = env('APP_KEY','chenbool');
    $token = [
        "iss" => env('APP_URL'), //签发者 可选
        "iat" => time(), //签发时间
        "nbf" => time(), // 某个时间点后才能访问,比如设置time()+30,表示当前时间30秒后才能使用
        "exp" => time()+7200,  //过期时间,这里设置2个小时
    ];
    // return JWT::encode($token, $key);
    return [
        'token'         =>  JWT::encode($token, $key),
        'iss'           =>   $token['iss'],
        'exp'           =>  $token['exp'],
        'exp_time'      =>  date('Y-m-d H:i:s',$token['exp'])
    ];
}
// 解密token
function jwt_decode($jwt,$key=null){
    $key || $key = env('APP_KEY','chenbool');
    try {
        $decoded = JWT::decode($jwt, $key, array('HS256'));
        return $decoded;
    } catch (Exception $e) {
        returnJson($e->getMessage(),-500);
    }
}


// 生成新的token 接口使用
function jwt_builder($jwt,$key=null){
    $key || $key = env('APP_KEY','chenbool');

    try {
        $decoded = JWT::decode($jwt, $key, array('HS256'));
        return jwt_encode();
    }catch(\chenbool\JWT\ExpiredException $e) {  
        return jwt_encode();
    } catch (Exception $e) {
        returnJson($e->getMessage(),-500);
    }    

}
